package com.homer.gps.track.activity;

import java.util.Locale;

import android.content.Context;
import android.os.Bundle;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.homer.gps.track.helper.LocaleDelegate;
import com.homer.gps.track.helper.UsefullStaff;
import com.homer.gps.track.persist.DatabaseHelper;
import com.homer.gps.track.persist.Repository;
import com.j256.ormlite.android.apptools.OpenHelperManager;

public abstract class DefaultORMSherlockActivity extends SherlockActivity{
	
	private Repository repository;
	private DatabaseHelper dbHelper = null;
	private Locale locale;
	
	private ActionBar bar;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Locale preferenceLocale = LocaleDelegate.getPreferenceLocale(this);
		// if the locale has not been stored in the preferences ...
		if (preferenceLocale == null) {
			// store the default preference locale
			preferenceLocale = Locale.getDefault();
			preferenceLocale = LocaleDelegate.getAcceptedLocale(this, preferenceLocale);
			LocaleDelegate.setPreferenceLocale(this, preferenceLocale);
		}
		// remember the locale
		this.locale = preferenceLocale;
		// update configuration to locale (if needed)
		LocaleDelegate.updateConfiguration(this, preferenceLocale);

		bar = getSupportActionBar();
		bar.setHomeButtonEnabled(Boolean.TRUE);
		bar.setDisplayShowHomeEnabled(Boolean.TRUE);
		bar.setDisplayHomeAsUpEnabled(Boolean.TRUE);
//		bar.setDisplayShowTitleEnabled(Boolean.FALSE);
//		bar.setDisplayShowCustomEnabled(Boolean.TRUE);
//		CharSequence titleText = getTitle(getResources());
//		setTitle(titleText);
	}

	public Repository getRepository(Context context) {
	    if (dbHelper == null) {
	        dbHelper = (DatabaseHelper)OpenHelperManager.getHelper(context, DatabaseHelper.class);
	    }
	    repository = new Repository(dbHelper);
	    return repository;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == android.R.id.home){
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onDestroy() {
		if (dbHelper != null) {
	        OpenHelperManager.releaseHelper();
	        dbHelper = null;
	    }
		super.onDestroy();
	}
	
	protected void onResume() {
		if (!LocaleDelegate.isPreferenceLocale(this, this.locale)) {
			UsefullStaff.restart(this);
		}

		super.onResume();
	}

}
